package com.jiangdg.demo

import android.content.Context
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.util.LruCache
import androidx.core.net.toUri
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object MediaCache {
    private lateinit var cache: LruCache<String, Bitmap>
    private val cacheSize = (Runtime.getRuntime().maxMemory() / 1024 / 8).toInt()


    fun initialize(context: Context) {
        if (!::cache.isInitialized) {
            val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
            val cacheSize = maxMemory / 8
            cache = LruCache(cacheSize)
        }
    }

    private val memoryCache: LruCache<String, Bitmap> = object : LruCache<String, Bitmap>(cacheSize) {
        override fun sizeOf(key: String, bitmap: Bitmap): Int {
            return bitmap.byteCount / 1024
        }
    }

    suspend fun getMediaFrame(mediaPath: String,context: Context): Bitmap? {
        return memoryCache.get(mediaPath) ?: extractAndCacheFrame(mediaPath,context)
    }

    private suspend fun extractAndCacheFrame(mediaPath: String,context: Context): Bitmap? {
        return withContext(Dispatchers.IO) {
            try {
                if (isVideoFile(mediaPath,context)) {
                    val retriever = MediaMetadataRetriever()
                    retriever.setDataSource(mediaPath)
                    val bitmap = retriever.frameAtTime
                    retriever.release()
                    memoryCache.put(mediaPath, bitmap)
                    bitmap
                } else {
                    val bitmap = Glide.with(context)
                        .asBitmap()
                        .load(mediaPath)
                        .submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get()
                    memoryCache.put(mediaPath, bitmap)
                    bitmap
                }
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }
    }

    private fun isVideoFile(filePath: String,context: Context): Boolean {
        val mimeType = context.contentResolver.getType(filePath.toUri())
        return mimeType?.startsWith("video/") == true
    }
}
